Fork me on GitHub

145. Binary Tree Postorder Traversal

Hard

Given a binary tree, return the postorder traversal of its nodes’ values.

Example:

1
2
3
4
5
6
7
8
Input: [1,null,2,3]
1
\
2
/
3

Output: [3,2,1]

Follow up: Recursive solution is trivial, could you do it iteratively?

  1. Recursive
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if not root: return []
res = []
self.dfs(root, res)
return res

def dfs(self, node, res):
if node:
self.dfs(node.left, res)
self.dfs(node.right, res)
res.append(node.val)
Shuolin Tian wechat
欢迎加我微信交流